#!/bin/bash -eu
#
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Set the $RANDFILE env var to where openssl expects it.
echo 'setting RANDFILE var value to /root/.rnd'
export RANDFILE="/root/.rnd"

source /opt/c2d/c2d-utils || exit 1

set +o errexit
passdb=$(get_attribute_value "zabbix-db-password")
passadmin=$(get_attribute_value "zabbix-admin-password")
configname=$(get_attribute_value "zabbix-config-name")
set -o errexit

if [[ ! -n "$passdb" ]]; then
  echo 'Generating random database password.'
  passdb=$(openssl rand -base64 12)
fi

if [[ ! -n "$passadmin" ]]; then
  passfile=/var/tmp/zabbix-admin-password
  echo 'Generating random admin password.'
  echo "Password is stored in $passfile file."
  echo 'Please, change it as soon as possible.'
  touch $passfile
  chown root:root $passfile
  chmod 600 $passfile
  passadmin=$(openssl rand -base64 12)
  echo "$passadmin" > $passfile
  if [[ -n "$configname" ]]; then
    echo 'Setting runtime variable.'
    gcloud beta runtime-config configs variables set zabbixPassword "$passadmin" --is-text --config-name "$configname"
  fi
fi

while ! pg_isready; do sleep 3; done
echo 'Setting passwords.'
su - postgres -c "psql -c \"alter role zabbix with password '${passdb}'\""
su - postgres -c "psql zabbix -c \"update users set passwd=md5('${passadmin}') where alias='Admin'\""

sed -i "s@^\$DB\['PASSWORD'\] =.*@\$DB['PASSWORD'] = '$passdb';@" /etc/zabbix/web/zabbix.conf.php
sed -i "s@^DBPassword=.*@DBPassword=$passdb@" /etc/zabbix/zabbix_server.conf

echo 'Restaring zabbix server.'
service zabbix-server restart
service zabbix-proxy restart
